<?php

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

if (!function_exists('cdn_url')){
    /**
     * @param mixed $url url地址
     * @param string $disk public
     * @return mixed
     */
    function cdn_url(mixed $url, string $disk = ''): mixed
    {
        if(!$url){
            return $url;
        }
        $upload = config('admin.upload');
        $disk = $disk?$disk:($upload['disk']?$upload['disk']:'public');
        if (is_string($url) && Str::contains($url, '//')) {
            return $url;
        }elseif(is_array($url)){
            $urls = [];
            foreach($url as $k=>$v){
                $urls[$k] = cdn_url($v,$disk);
            }
            return $urls;
        }else{
            return Storage::disk($disk)->url($url);
        }
    }
}

if (!function_exists('toUnderLine')){
    /**
     * 字符串转骆驼峰
     * @param $str
     * @return array|string|string[]|null
     */
    function toUnderLine($str){
        return preg_replace_callback('/([-_\/]+([a-z]))/i',function($matches){
            return strtoupper($matches[2]);
        },$str);
    }
}


if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size      大小
     * @param string $delimiter 分隔符
     * @param int $precision 小数位数
     * @return string
     */
    function format_bytes(int $size, string $delimiter = '', int $precision = 2): string
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}


if (!function_exists('modelError')){
    function modelError($message,$data = []){
        admin_exit(Admin::json()->error($message)->data($data));
    }
}

if (!function_exists('modelSuccess')){
    function modelSuccess($message,$data = []){
        admin_exit(Admin::json()->success($message)->data($data));
    }
}

if (!function_exists('show_error')){
    /**
     * @param $validator
     * @param string $field
     * @return mixed|string
     */
    function show_error($validator,string $field = ''){
        $errors = $validator->errors();
        if (!$field){
            $all = $errors->all();
        }else{
            $all = $errors->get($field);
        }
        foreach ($all as $message){
            return $message;break;
        }
        return "validator验证出错";
    }
}


if(!function_exists('is_dir_mkdir')) {
    /**
     * 判断文件路径是否存在，不存在则生成
     * @param string $filePath 文件路径
     */
    function is_dir_mkdir($filePath)
    {
        if (!is_dir($filePath)) {
            mkdir($filePath, 0755, true);
        }
    }
}


if(!function_exists('sort_array_multi')){
    /**
     * @param array $arr
     * @param array $keys
     * @param array $order
     * @return bool|mixed
     */

    function sort_array_multi(array &$arr, array $keys, array $order)
    {
        //校验参数
        if ( count($keys) == ($times = count($order)) ) {
            for ( $i = 0, $j = 0; $j < $times; $i += 2, $j++ ) {
                foreach ( $arr as $k => $v ) {
                    //原数组是否存在该字段
                    if ( isset($v[$keys[$j]]) ) {
                        // $params[$i][] = $v[$keys[$j]];    //TODO 中文排序支持
                        $params[$i][] = iconv('UTF-8', 'GBK', $v[$keys[$j]]);
                    } else {
                        return false;
                    }
                }
                if ( strtoupper($order[$j]) == 'ASC' ) {
                    $params[$i + 1] = SORT_ASC;
                } else {
                    $params[$i + 1] = SORT_DESC;
                }
            }
            $params[] = &$arr;
            return call_user_func_array('array_multisort', $params);
        } else {
            return false;
        }
    }
}


if (!function_exists('del_dir')){
    /**
     * 删除文件夹级文件
     * @param $dir
     * @return bool
     */
    function del_dir($dir) {
        //先删除目录下的文件：
        $dh = opendir($dir);
        while ($file=readdir($dh)) {
            if($file!="." && $file!="..") {
                $fullpath= $dir."/".$file;
                if(!is_dir($fullpath)) {
                    @unlink($fullpath);
                } else {
                    del_dir($fullpath);
                }
            }
        }
        closedir($dh);
        //删除当前文件夹：
        if(rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}


if (!function_exists('build_order_no')) {
    /**
     * 生成随机订单号
     */
    function build_order_no(){
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . random_int(100000,999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_id;
    }
}



if (!function_exists('base64_image_content')) {
    /**
     * [base64_image_content description]
     * @param $base64_image_content
     * @param $path
     * @param $filename
     * @return false|string [type]                       [description]
     */
    function base64_image_content($base64_image_content, $path, $filename = null){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $content = base64_decode(str_replace($result[1], '', $base64_image_content));
            $path = trim($path,"/");
            $new_file = $filename?$path."/".$filename:$path."/".Str::uuid().".{$type}";
            Storage::disk(config('admin.upload.disk'))->put($new_file, $content);
            return $new_file;
        }else{
            if($base64_image_content&&Str::contains($base64_image_content,"/storage/")){
                return explode("/storage/",$base64_image_content)[1];
            }
            return $base64_image_content;
        }
    }
}

if (!function_exists('saveImages')){
    /**
     * 保存图片资源
     * @param array $sources
     * @param string $idNo
     * @param string $path
     * @return array
     */
    function saveImages(array $sources, string $idNo, string $path = ''): array
    {
        $images = [];
        foreach ($sources as $key=>$source){
            if (isset($source['content'])){
                $filename = $path."_".$idNo."_".$key.".png";
                $images[] = base64_image_content($source['content'],$path,$filename);
            }else{
                $images[] = str_replace("/storage/","",$source['url']);
            }
        }
        return $images;
    }
}


if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @param int $n 位数
     * @return string
     */
    function letter_avatar($text, int $n = 1)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, $n));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('getDistance')) {
    /**
     * 计算两点之间的距离
     * @param $lng1 经度1
     * @param $lat1 纬度1
     * @param $lng2 经度2
     * @param $lat2 纬度2
     * @param int $unit m，km
     * @param int $decimal 位数
     * @return float
     */
    function getDistance($lng1, $lat1, $lng2, $lat2, $unit = 2, $decimal = 2)
    {

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI           = 3.1415926535898;

        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;

        $radLng1 = $lng1 * $PI / 180.0;
        $radLng2 = $lng2 * $PI / 180.0;

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;

        if ($unit === 2) {
            $distance /= 1000;
        }

        return round($distance, $decimal);
    }

}





